﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Input;
using uTorrentNetClient.ModelDesign.Helper;
using Microsoft.Practices.Composite.Presentation.Commands;
using Microsoft.Win32;
using System.Windows;
using Cleverscape.UTorrentClient.WebClient;
using uTorrentNetClient.ModelDesign.Settings.View;
using uTorrentNetClient.ModelDesign.ConfigurationHandling;
using uTorrentNetClient.ModelDesign.FileHandling;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Threading;
using uTorrentNetClient.ModelDesign.Contracts;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Composite.Events;
using uTorrentNetClient.ModelDesign.Events;

namespace uTorrentNetClient.ModelDesign.Main.Model
{

    public class MainModel : Base, IMainModel
    {
        private readonly IUnityContainer _container;
        private readonly IEventAggregator _eventagregator;
        private readonly INotifyWindowView _notifyWindowView;

        private UTorrentWebClient _webClient;
        private string _selectedHash = string.Empty;
        private Dispatcher _guiDispatcher;
        private bool _addNewFile = false;
        private Timer _disconnctedTimer = null;
        private bool isNewTorrent = false;

        private bool updating = false;

        private List<Torrent> _allTorrents;

        private ISettingsController _settingsController;
        private IPropertiesController _propertiesController;
        private IEditSettingsController _editSettingsController;

        public IMainView View { get; set; }


        private ObservableCollection<TorrentDecorator> _torrents;
        public ObservableCollection<TorrentDecorator> Torrents
        {
            get { return _torrents; }
            set
            {
                _torrents = value;
                SetNotifyPropertyChanged("Torrents");
            }
        }

        private ObservableCollection<TorrentGroup> _groups;
        public ObservableCollection<TorrentGroup> Groups
        {
            get { return _groups; }
            set
            {
                _groups = value;
                SetNotifyPropertyChanged("Groups");
            }
        }

        private AppSetting _appSetting;
        public AppSetting AppSetting
        {
            get { return _appSetting; }
            set
            {
                _appSetting = value;
                SetNotifyPropertyChanged("AppSetting");
            }
        }

        private TorrentDecorator _selectedTorrent;
        public TorrentDecorator SelectedTorrent
        {
            get { return _selectedTorrent; }
            set
            {
                _selectedTorrent = value;
                if (_selectedTorrent != null)
                {
                    _selectedHash = _selectedTorrent.Hash;
                }
                SetNotifyPropertyChanged("SelectedTorrent");
            }
        }

        private ObservableCollection<ProtokollHelper> _protokoll;
        public ObservableCollection<ProtokollHelper> Protokoll
        {
            get { return _protokoll; }
            set
            {
                _protokoll = value;
                SetNotifyPropertyChanged("Protokoll");
            }
        }

        private TorrentGroup _selectedGroup;
        public TorrentGroup SelectedGroup
        {
            get { return _selectedGroup; }
            set
            {
                _selectedGroup = value;
                SetNotifyPropertyChanged("SelectedGroup");
                refresh();
            }
        }

        private TorrentFileDecorator _selectedFile;
        public TorrentFileDecorator SelectedFile
        {
            get { return _selectedFile; }
            set
            {
                _selectedFile = value;
                SetNotifyPropertyChanged("SelectedFile");
            }
        }

        private bool _connected;
        public bool Connected
        {
            get { return _connected; }
            set
            {
                _connected = value;
                SetNotifyPropertyChanged("Connected");
            }
        }

        private string _totalInfo;
        public string TotalInfo
        {
            get { return _totalInfo; }
            set
            {
                _totalInfo = value;
                SetNotifyPropertyChanged("TotalInfo");
            }
        }


        public DelegateCommand<object> OpenTorrentFileCommand { get; set; }
        public DelegateCommand<object> StartCommand { get; set; }
        public DelegateCommand<object> PauseCommand { get; set; }
        public DelegateCommand<object> StopCommand { get; set; }
        public DelegateCommand<object> RemoveCommand { get; set; }
        public DelegateCommand<object> SettingsCommand { get; set; }
        public DelegateCommand<object> PropertiesCommand { get; set; }
        public DelegateCommand<object> RefreshCommand { get; set; }
        public DelegateCommand<object> SetFileNoDownloadCommand { get; set; }
        public DelegateCommand<object> SetFileNormalCommand { get; set; }
        public DelegateCommand<object> SetFileHighCommand { get; set; }
        public DelegateCommand<object> SetFileLowCommand { get; set; }
        public DelegateCommand<object> ClearProtokollCommand { get; set; }

        public MainModel(IMainView view, IUnityContainer container, IEventAggregator eventagregator, INotifyWindowView notifyWindowView)
        {
            _container = container;
            _eventagregator = eventagregator;
            _notifyWindowView = notifyWindowView;
            View = view;
            View.DataContext = this;

            _guiDispatcher = Dispatcher.CurrentDispatcher;

            Protokoll = new ObservableCollection<ProtokollHelper>();

            OpenTorrentFileCommand = new DelegateCommand<object>(openTorrentFileCommandExcecute);
            StartCommand = new DelegateCommand<object>(startCommandExcecute);
            PauseCommand = new DelegateCommand<object>(pauseCommandExcecute);
            StopCommand = new DelegateCommand<object>(stopCommandExcecute);
            RemoveCommand = new DelegateCommand<object>(removeCommandExcecute);
            SettingsCommand = new DelegateCommand<object>(settingsCommandExcecute);
            PropertiesCommand = new DelegateCommand<object>(propertiesCommandExcecute);
            SetFileNoDownloadCommand = new DelegateCommand<object>(fileNoDownloadCommandExcecute);
            SetFileNormalCommand = new DelegateCommand<object>(fileNormalCommandExcecute);
            SetFileHighCommand = new DelegateCommand<object>(fileHighCommandExcecute);
            SetFileLowCommand = new DelegateCommand<object>(fileLowCommandExcecute);
            RefreshCommand = new DelegateCommand<object>(refreshCommandExcecute);
            ClearProtokollCommand = new DelegateCommand<object>(clearProtokollCommandExcecute);

            eventagregator.GetEvent<CloseSettingsEvent>().Subscribe(closeSettings);
            eventagregator.GetEvent<ClosePropertiesEvent>().Subscribe(closeProperties);
            eventagregator.GetEvent<CloseEditSettingsEvent>().Subscribe(closeEditSettings);

            try
            {
                setGroups();
                loadSettings();
                connect();
            }
            catch (Exception ex)
            {
                Protokoll.Add(new ProtokollHelper(ProtokollHelperType.ERROR, ex.Message));
            }
        }



        private void closeProperties(bool add)
        {
            if (_propertiesController != null)
            {
                _propertiesController.ClosePropertiesCommand.Execute(null);
                _propertiesController = null;

                if (add)
                {
                    isNewTorrent = false;
                    startTorrent(SelectedTorrent);
                    refresh();
                }
                else
                {
                    if (isNewTorrent)
                    {
                        isNewTorrent = false;
                        removeTorrent(SelectedTorrent, false);
                    }
                }
            }
        }

        private void setGroups()
        {
            Groups = null;
            Groups = new ObservableCollection<TorrentGroup>();
            Groups.Add(new TorrentGroup
            {
                GroupType = TorrentGroupsType.Aktive,
                Name = "Aktiv",
                SortNumber = 3,
                SimpleStates = new List<TorrentSimpleStatus>
                                    {
                                        TorrentSimpleStatus.DownloadingQueued,
                                        TorrentSimpleStatus.Downloading,
                                        TorrentSimpleStatus.DownloadingError,
                                        TorrentSimpleStatus.SeedingQueued,
                                        TorrentSimpleStatus.Seeding,
                                        TorrentSimpleStatus.SeedingError,
                                    }
            });
            Groups.Add(new TorrentGroup
            {
                GroupType = TorrentGroupsType.Downloading,
                Name = "Download",
                SortNumber = 1,
                SimpleStates = new List<TorrentSimpleStatus>
                                    {
                                        TorrentSimpleStatus.DownloadingQueued,
                                        TorrentSimpleStatus.Downloading,
                                        TorrentSimpleStatus.DownloadingError
                                    }
            });
            Groups.Add(new TorrentGroup
            {
                GroupType = TorrentGroupsType.Ready,
                Name = "Fertig",
                SortNumber = 2,
                SimpleStates = new List<TorrentSimpleStatus>
                                    {
                                        TorrentSimpleStatus.SeedingQueued,
                                        TorrentSimpleStatus.Seeding,
                                        TorrentSimpleStatus.SeedingError,
                                        TorrentSimpleStatus.InactiveCompleted,
                                    }
            });
            Groups.Add(new TorrentGroup
            {
                GroupType = TorrentGroupsType.All,
                Name = "Alle",
                SortNumber = 0,
                SimpleStates = new List<TorrentSimpleStatus>
                                    {
                                        TorrentSimpleStatus.DownloadingQueued,
                                        TorrentSimpleStatus.Downloading,
                                        TorrentSimpleStatus.DownloadingError,
                                        TorrentSimpleStatus.InactiveIncomplete,
                                        TorrentSimpleStatus.SeedingQueued,
                                        TorrentSimpleStatus.Seeding,
                                        TorrentSimpleStatus.SeedingError,
                                        TorrentSimpleStatus.InactiveCompleted,
                                        TorrentSimpleStatus.Paused,
                                        TorrentSimpleStatus.Error
                                    }
            });
            Groups.Add(new TorrentGroup
            {
                GroupType = TorrentGroupsType.NoAktive,
                Name = "Nicht Aktiv",
                SortNumber = 4,
                SimpleStates = new List<TorrentSimpleStatus>
                                    {
                                        TorrentSimpleStatus.InactiveIncomplete,
                                        TorrentSimpleStatus.InactiveCompleted,
                                        TorrentSimpleStatus.Paused,
                                        TorrentSimpleStatus.Error
                                    }
            });

            SelectedGroup = Groups[0];
        }

        private void loadSettings()
        {
            try
            {
                //var settings = new AppSetting { Server = "localhost", Port = 8080, User = "admin", Password = "framework", RefreshSec = 10 };

                var path = Path.Combine(new ConfigRepository().SettingsPath, "Settings.xml");

                if (FileHandler.FileExists(path))
                {
                    AppSetting = FileHandler.LoadFromXML<AppSetting>(path);
                    AppSetting.ResetChanges();
                }
                else
                    AppSetting = new AppSetting();
            }
            catch (Exception ex)
            {
                if (Protokoll != null)
                    Protokoll.Add(new ProtokollHelper(ProtokollHelperType.ERROR, ex.Message));

                AppSetting = new AppSetting();
            }

            if (AppSetting.ShowNotifyWindow)
                _notifyWindowView.ShowView();
            else
                _notifyWindowView.CloseView();
        }

        private void saveSettings()
        {
            try
            {
                var path = Path.Combine(new ConfigRepository().SettingsPath, "Settings.xml");

                FileHandler.SaveToXML(AppSetting, path);

                AppSetting.ResetChanges();
            }
            catch (Exception ex)
            {
                Protokoll.Add(new ProtokollHelper(ProtokollHelperType.ERROR, ex.Message));
            }

            if (AppSetting.ShowNotifyWindow)
                _notifyWindowView.ShowView();
            else
                _notifyWindowView.CloseView();
        }

        private void connect()
        {
            if (_guiDispatcher.Thread != Thread.CurrentThread)
                _guiDispatcher.Invoke(DispatcherPriority.DataBind, (ThreadStart)delegate { connect(); });
            else
            {
                if (_webClient != null)
                {
                    disconnect();
                }

                if (AppSetting != null)
                {
                    try
                    {
                        _webClient = new UTorrentWebClient(AppSetting.Server + ":" + AppSetting.Port, AppSetting.User, AppSetting.Password, true, AppSetting.RefreshSec);
                        _webClient.TorrentAdded += new TorrentEventHandler(_webClient_TorrentAdded);
                        _webClient.TorrentFinishedDownloading += new TorrentEventHandler(_webClient_TorrentFinishedDownloading);
                        _webClient.TorrentPaused += new TorrentEventHandler(_webClient_TorrentPaused);
                        _webClient.TorrentStarted += new TorrentEventHandler(_webClient_TorrentStarted);
                        _webClient.TorrentStopped += new TorrentEventHandler(_webClient_TorrentStopped);
                        _webClient.TorrentsUpdated += new EventHandler(_webClient_TorrentsUpdated);
                        _webClient.TorrentUnPaused += new TorrentEventHandler(_webClient_TorrentUnPaused);

                        if(!updating)
                            refresh();

                        Connected = true;
                        if(_disconnctedTimer != null)
                            _disconnctedTimer.Dispose();
                        _disconnctedTimer = null;
                        Protokoll.Add(new ProtokollHelper(ProtokollHelperType.INFO, "Connected to uTorrent-Server"));
                    }
                    catch (Exception ex)
                    {
                        Protokoll.Add(new ProtokollHelper(ProtokollHelperType.ERROR, ex.Message));
                        disconnect();
                    }
                    finally
                    {
                        GC.Collect();
                    }
                }
            }
        }

        private void refresh()
        {
            if (_guiDispatcher.Thread != Thread.CurrentThread)
                _guiDispatcher.Invoke(DispatcherPriority.DataBind, (ThreadStart)delegate { refresh(); });
            else
            {

                if (_webClient != null)
                {
                    if (!updating)
                    {
                        updating = true;

                        try
                        {
                            if (Torrents != null)
                            {
                                Torrents = null;
                            }
                            Torrents = new ObservableCollection<TorrentDecorator>();

                            if (_webClient.AutoUpdate)
                            {
                                _allTorrents = null;
                                _allTorrents = new List<Torrent>();
                                foreach (var torrent in _webClient.Torrents)
                                {
                                    _allTorrents.Add(torrent);

                                    if (SelectedGroup.SimpleStates.Count(x => x == torrent.SimpleStatus) > 0)
                                        Torrents.Add(new TorrentDecorator(torrent));
                                }

                                calcTotalInfo();
                            }
                            else
                            {
                                updating = false;
                                disconnect();
                            }

                            GC.Collect();
                        }
                        catch (Exception ex)
                        {
                            Protokoll.Add(new ProtokollHelper(ProtokollHelperType.ERROR, ex.Message));
                            disconnect();
                        }
                        finally
                        {
                            updating = false;
                        }
                    }

                    if (Torrents != null)
                        SelectedTorrent = Torrents.FirstOrDefault(x => x.Hash == _selectedHash);

                    if (StartupFile.File.Count > 0 && Connected)
                    {
                        var file = StartupFile.File.FirstOrDefault();

                        StartupFile.File.Remove(file);

                        if (File.Exists(file))
                        {
                            _addNewFile = true;
                            _webClient.AddTorrent(file);
                        }
                    }
                }
                else
                {
                    try
                    {
                        connect();
                    }
                    catch (Exception ex)
                    {
                        Protokoll.Add(new ProtokollHelper(ProtokollHelperType.ERROR, ex.Message));
                    }
                }
            }
        }

        private void disconnect()
        {
            if (_guiDispatcher.Thread != Thread.CurrentThread)
                _guiDispatcher.Invoke(DispatcherPriority.DataBind, (ThreadStart)delegate { disconnect(); });
            else
            {
                if (_webClient != null)
                {
                    Torrents = null;

                    _webClient.Dispose();
                    _webClient = null;
                    Connected = false;
                    if (_disconnctedTimer == null && AppSetting != null)
                    {
                        _disconnctedTimer = new Timer(new TimerCallback(delegate(object o) { connect(); }), new object(), TimeSpan.FromSeconds(AppSetting.RefreshSec), TimeSpan.FromSeconds(AppSetting.RefreshSec));
                    }
                    Protokoll.Add(new ProtokollHelper(ProtokollHelperType.WARNING, "Disconnected from uTorrent-Server"));
                }
                else
                {
                    if (_disconnctedTimer == null && AppSetting != null)
                    {
                        _disconnctedTimer = new Timer(new TimerCallback(delegate(object o) { connect(); }), new object(), TimeSpan.FromSeconds(AppSetting.RefreshSec), TimeSpan.FromSeconds(AppSetting.RefreshSec));
                    }
                }
            }

            GC.Collect();
        }

        private void addTorrentFile()
        {
            if (_webClient != null)
            {
                var fileDialog = new OpenFileDialog();
                fileDialog.Filter = "Torrent|*.torrent";
                fileDialog.Multiselect = false;
                var result = fileDialog.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    _addNewFile = true;
                    _webClient.AddTorrent(fileDialog.FileName);
                }
            }
        }

        private void addFileExecute()
        {
            if (_addNewFile && AppSetting.ShowDialogOnNewTorrent)
            {
                var newTorrent = _webClient.Torrents.FirstOrDefault(x => x.Hash == _selectedHash);
                if (newTorrent != null)
                {
                    stopTorrent(new TorrentDecorator(newTorrent));
                    _addNewFile = false;
                    isNewTorrent = true;
                    showProperties(newTorrent);
                }
            }
            else
            {
                refresh();
                var newTorrent = _webClient.Torrents.FirstOrDefault(x => x.Hash == _selectedHash);
                _eventagregator.GetEvent<ShowBalloonTipEvent>().Publish(newTorrent.Name + " wurde hinzugefügt.");
            }
        }

        private void startTorrent(TorrentDecorator torrentD)
        {
            if (_webClient != null && torrentD != null)
            {
                _webClient.TorrentStart(torrentD.Torrent);
            }
        }

        private void stopTorrent(TorrentDecorator torrentD)
        {
            if (_webClient != null && torrentD != null)
            {
                _webClient.TorrentStop(torrentD.Torrent);
            }
        }

        private void pauseunpauseTorrent(TorrentDecorator torrentD)
        {
            if (_webClient != null && torrentD != null)
            {
                if (torrentD.SimpleStatus == TorrentSimpleStatus.Paused)
                    _webClient.TorrentUnPause(torrentD.Torrent);
                else if (torrentD.SimpleStatus == TorrentSimpleStatus.Downloading ||
                    torrentD.SimpleStatus == TorrentSimpleStatus.DownloadingQueued ||
                    torrentD.SimpleStatus == TorrentSimpleStatus.Seeding ||
                    torrentD.SimpleStatus == TorrentSimpleStatus.SeedingQueued ||
                    torrentD.SimpleStatus == TorrentSimpleStatus.DownloadingError ||
                    torrentD.SimpleStatus == TorrentSimpleStatus.SeedingError)
                    _webClient.TorrentPause(torrentD.Torrent);
            }
        }

        private void removeTorrent(TorrentDecorator torrentD, bool withDialog)
        {
            if (_webClient != null && torrentD != null)
            {
                if (withDialog)
                {
                    var result = MessageBox.Show("Heruntergeladene Dateien auch löschen?", "Löschen",
                                                 MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                        _webClient.TorrentRemove(torrentD.Torrent, true);
                    else if (result == MessageBoxResult.No)
                        _webClient.TorrentRemove(torrentD.Torrent, false);
                }
                else
                {
                    _webClient.TorrentRemove(torrentD.Torrent, true);
                }
                refresh();
            }
        }

        private void recheckTorrent(TorrentDecorator torrentD)
        {
            if (_webClient != null && torrentD != null)
            {
                _webClient.TorrentReCheck(torrentD.Torrent);
            }
        }

        private void setFilePriority(FilePriority priority)
        {
            SelectedFile.Priority = priority;
            if (SelectedFile.HasChanges)
            {
                SelectedFile.SaveChanges();
                refresh();
            }
        }

        private void closeSettings(CloseSettingsHelper closeSettingsHelper)
        {
            if (_settingsController != null)
            {
                _settingsController.CloseSettingsCommand.Execute(null);
                _settingsController = null;

                if (closeSettingsHelper != null && closeSettingsHelper.ShowEditSettings)
                {
                    if (_editSettingsController == null)
                        _editSettingsController = _container.Resolve<IEditSettingsController>();

                    _editSettingsController.ShowEditSettingsCommand.Execute(closeSettingsHelper.GroupMappings);
                }

                if (closeSettingsHelper != null && closeSettingsHelper.AppSetting != null && closeSettingsHelper.AppSetting.HasChanges)
                {
                    try
                    {
                        AppSetting = closeSettingsHelper.AppSetting;
                        saveSettings();
                        disconnect();
                        connect();
                    }
                    catch (Exception ex)
                    {
                        Protokoll.Add(new ProtokollHelper(ProtokollHelperType.ERROR, ex.Message));
                    }
                }
            }
        }

        private void closeEditSettings(object obj)
        {
            if (_editSettingsController != null)
            {
                _editSettingsController.CloseEditSettingsCommand.Execute(null);
                _editSettingsController = null;

                if (_settingsController == null)
                {
                    _settingsController = _container.Resolve<ISettingsController>();
                    _settingsController.ShowSettingsCommand.Execute(new SettingsCommandHelper(AppSetting, _webClient));
                }
            }
        }

        private void showProperties(Torrent torrent)
        {
            if (_propertiesController == null)
            {
                _propertiesController = _container.Resolve<IPropertiesController>();
                _propertiesController.ShowPropertiesCommand.Execute(new TorrentDecorator(torrent));
            }
        }

        private void calcTotalInfo()
        {
            var states = new List<TorrentSimpleStatus>
                             {
                                 TorrentSimpleStatus.DownloadingQueued,
                                 TorrentSimpleStatus.Downloading,
                                 TorrentSimpleStatus.DownloadingError,
                                 TorrentSimpleStatus.SeedingQueued,
                                 TorrentSimpleStatus.Seeding,
                                 TorrentSimpleStatus.SeedingError
                             };

            var activeT = _allTorrents.Where(x => states.Contains(x.SimpleStatus));

            var countAll = _allTorrents.Count;
            var countActiv = activeT.Count();
            var speedUp = Utilities.FormatFileSize(activeT.Sum(x => x.SpeedUploadBytes),
                                                   Utilities.FileSizeFormat.SpeedBytes);
            var speedDown = Utilities.FormatFileSize(activeT.Sum(x => x.SpeedDownloadBytes),
                                                   Utilities.FileSizeFormat.SpeedBytes);

            TotalInfo = "Torrents: " + countActiv + "/" + countAll + " | Down: " + speedDown + " | Up: " +
                        speedUp;

            _eventagregator.GetEvent<UpdateSpeedDownInfoEvent>().Publish(new SpeedHelper(activeT.Sum(x => x.SpeedDownloadBytes)));
            _eventagregator.GetEvent<UpdateSpeedUpInfoEvent>().Publish(new SpeedHelper(activeT.Sum(x => x.SpeedUploadBytes)));
            _eventagregator.GetEvent<UpdateNotifyToolTipInfoEvent>().Publish(TotalInfo);
        }

        #region Commands

        private void openTorrentFileCommandExcecute(object o)
        {
            addTorrentFile();
        }

        private void startCommandExcecute(object o)
        {
            startTorrent(SelectedTorrent);
        }

        private void pauseCommandExcecute(object o)
        {
            pauseunpauseTorrent(SelectedTorrent);
        }

        private void stopCommandExcecute(object o)
        {
            stopTorrent(SelectedTorrent);
        }

        private void removeCommandExcecute(object o)
        {

            removeTorrent(SelectedTorrent, true);
        }

        private void settingsCommandExcecute(object o)
        {
            if (_settingsController == null)
            {
                _settingsController = _container.Resolve<ISettingsController>();
                _settingsController.ShowSettingsCommand.Execute(new SettingsCommandHelper(AppSetting, _webClient));
            }
        }

        private void propertiesCommandExcecute(object o)
        {
            showProperties(SelectedTorrent.Torrent);
        }

        private void refreshCommandExcecute(object o)
        {
            refresh();
        }

        //private bool commandCanExcecute(object o)
        //{
        //    if (Connected)
        //        return true;
        //    else
        //        return false;
        //}

        private void fileNoDownloadCommandExcecute(object o)
        {
            setFilePriority(FilePriority.DontDownload);
        }

        private void fileNormalCommandExcecute(object o)
        {
            setFilePriority(FilePriority.NormalPriority);
        }

        private void fileHighCommandExcecute(object o)
        {
            setFilePriority(FilePriority.HighPriority);
        }

        private void fileLowCommandExcecute(object o)
        {
            setFilePriority(FilePriority.LowPriority);
        }

        private void clearProtokollCommandExcecute(object o)
        {
            Protokoll = null;
            Protokoll = new ObservableCollection<ProtokollHelper>();
        }

        #endregion

        #region WebClient Events
        void _webClient_TorrentUnPaused(object sender, TorrentEventArgs e)
        {
            if (!updating)
                refresh();
        }

        void _webClient_TorrentsUpdated(object sender, EventArgs e)
        {
            if (!updating)
                refresh();
        }

        void _webClient_TorrentStopped(object sender, TorrentEventArgs e)
        {
            if (!updating)
                refresh();
        }

        void _webClient_TorrentStarted(object sender, TorrentEventArgs e)
        {
            if (!updating)
                refresh();
        }

        void _webClient_TorrentPaused(object sender, TorrentEventArgs e)
        {
            if (!updating)
                refresh();
        }

        void _webClient_TorrentFinishedDownloading(object sender, TorrentEventArgs e)
        {
            if (!updating)
                refresh();

            _eventagregator.GetEvent<ShowBalloonTipEvent>().Publish(e.Torrent.Name + " wurde fertig.");
        }

        void _webClient_TorrentAdded(object sender, TorrentEventArgs e)
        {
            _selectedHash = e.Torrent.Hash;
            addFileExecute();
        }
        #endregion
    }
}
